import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref(null)
  const token = ref(localStorage.getItem('access_token'))
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 动作
  const setAuth = (userData, accessToken) => {
    user.value = userData
    token.value = accessToken
    localStorage.setItem('access_token', accessToken)
    
    // 设置 axios 默认请求头
    api.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`

    // 切换/首次登录后，清空与装修表单相关的本地缓存，避免上一用户数据残留
    try {
      localStorage.removeItem('decoration_form_data')
      localStorage.removeItem('decoration_uploaded_file')
      localStorage.removeItem('decoration_current_request')
      localStorage.removeItem('decoration_request_id')
    } catch {}
  }

  const clearAuth = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('access_token')
    delete api.defaults.headers.common['Authorization']

    // 登出时一并清理装修相关的缓存
    try {
      localStorage.removeItem('decoration_form_data')
      localStorage.removeItem('decoration_uploaded_file')
      localStorage.removeItem('decoration_current_request')
      localStorage.removeItem('decoration_request_id')
    } catch {}
  }

  const login = async (phone, password) => {
    try {
      loading.value = true
      const response = await api.post('/auth/login', {
        phone,
        password
      })
      
      if (response.data.success) {
        setAuth(response.data.user, response.data.access_token)
        return response.data
      } else {
        throw new Error(response.data.error || '登录失败')
      }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const register = async (phone, password) => {
    try {
      loading.value = true
      const response = await api.post('/auth/register', {
        phone,
        password
      })
      
      if (response.data.success) {
        setAuth(response.data.user, response.data.access_token)
        return response.data
      } else {
        throw new Error(response.data.error || '注册失败')
      }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const logout = async () => {
    try {
      if (token.value) {
        await api.post('/auth/logout')
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      clearAuth()
    }
  }

  const fetchProfile = async () => {
    try {
      if (!token.value) return
      
      const response = await api.get('/auth/profile')
      if (response.data.success) {
        user.value = response.data.user
        return response.data.user
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果 token 无效，清除认证状态
      if (error.response?.status === 401) {
        clearAuth()
      }
    }
  }

  // 初始化时设置 axios 请求头
  if (token.value) {
    api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }

  return {
    // 状态
    user,
    token,
    loading,
    
    // 计算属性
    isAuthenticated,
    
    // 动作
    setAuth,
    clearAuth,
    login,
    register,
    logout,
    fetchProfile
  }
})
